<template>
	<view>
		<view class="u-flex u-p-l-20 u-p-r-20">
			<u-input class="u-m-r-20" v-model="name" border  placeholder="请输入老板名称"/>
			<u-button size="medium" type="primary" @click="handleAddBoss">添加</u-button>
		</view>
		<view class="border-y u-text-center u-m-t-20 u-p-20">老板列表</view>
		<view class="content u-text-center">
			<view class="u-flex u-p-20 border-y margin-top--1" style="background-color: #f5f5f5;font-weight:bold;">
				<view class="u-flex-1">老板</view>
				<view class="w30 ">操作</view>
			</view>
			<view class="u-flex u-p-20 border-y margin-top--1" v-for="item in bossList" :key="item.name">
				<view class="u-flex-1">
					<text v-if="!item.update">{{ item.name }}</text>
					<u-input v-if="item.update" :focus="item.update" v-model="item.name" border></u-input>
				</view>
				<view v-if="!item.update" class="w30">
					<u-button class="u-m-r-20" size="mini" type="primary" @click="item.update = true">{{ '修改' }}
					</u-button>
					<u-button size="mini" type="error" @click="handleDelete(item)">{{ '删除'}}</u-button>
				</view>
				<view v-if="item.update" class="w30">
					<u-button class="u-m-r-20" size="mini" @click="$set(item,'update',false)">取消</u-button>
					<u-button size="mini" type="primary" @click="handleUpdate(item)">确定</u-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				name: '',
				bossList: [],
				updateName: ''
			}
		},
		created() {
			this.getBossList()
		},
		methods: {
			// 添加
			async handleAddBoss() {
				if(this.name === ''){
					this.$u.toast('请输入老板名称')
					return
				}
				try {
					const res = await this.$u.post('/bosses', {
						name: this.name
					})
					this.$u.toast('添加成功')
					this.getBossList()
					this.name = ''
				} catch (err) {
					if (err.statusCode === 422) {
						this.$u.toast('已经存在，不能重复添加!');
					}
				}
			},
			// 获取Boss列表
			async getBossList() {
				const res = await this.$u.get('/bosses')
				console.log(res)
				this.bossList = res.map(item => {
					item.update = false
					return item
				})
			},
			// 修改
			async handleUpdate(item) {
				const res = await this.$u.put(`/rest/bosses/${item._id}`, {
					name: item.name
				})
				this.$u.toast(res.message)
				this.getBossList()
			},
			// 删除
			async handleDelete(item){
				uni.showModal({
				    title: '警告',
				    content: `确定要删除${item.name}吗？此操作不可恢复！`,
				    success: async (res)=> {
				        if (res.confirm) {
				            const res = await this.$u.delete(`/rest/bosses/${item._id}`)
				            this.$u.toast(res.message)
				            this.getBossList()
				        }
				    }
				})
			}

		}
	}
</script>

<style>
	.w30 {
		width: 30%;
	}
</style>
